﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;


namespace search
{
	/// <summary>
	/// SSearch 的摘要说明。
	/// </summary>
	public partial class KeySearch : System.Web.UI.Page
	{
		private const int PAGE_SIZE = 8;
		private bool flag = true;

	
		protected void Page_Load(object sender, System.EventArgs e)
		{
			// 在此处放置用户代码以初始化页面
			if(!Page.IsPostBack)
			{
				CheckUser();
				//				if(Session["searchkey"] != null && Session["searchkey"].ToString() != "")
				//				{
				//					string key = Session["searchkey"].ToString();
				//					Session["searchkey"] = null;
				//					Search(key);
				//					this.TextBox_Key.Text = key;
				//				}
				if(Request["key"] != null && Request["key"].ToString() != "")
				{
					string key = Server.HtmlDecode(Request["key"].ToString());
					this.TextBox_Key.Text = key;
					Search(GetArrString(key), 1);
				}
				this.TextBox_Key.Attributes["onKeyPress"] = "if(event.keyCode==13){location.href='keysearch.aspx?key=' + document.all('TextBox_Key').value;return false;}";
			}
		}

		#region Web 窗体设计器生成的代码
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// 设计器支持所需的方法 - 不要使用代码编辑器修改
		/// 此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{    
			this.DataList1.ItemDataBound += new System.Web.UI.WebControls.DataListItemEventHandler(this.DataList1_ItemDataBound);

		}
		#endregion

		private void CheckUser()
		{
			
			this.Literal_Admin.Text = "";
			HttpCookie emailCookie = Request.Cookies["Email"];
			if(emailCookie == null)
			{
				return;
			}
			DataSet ds = SearchDataAccess.GetUserRoles(emailCookie.Value);
			ds.Tables[0].DefaultView.RowFilter = "RoleID=4";
			if(ds.Tables[0].DefaultView.Count > 0)
			{
				this.Literal_Admin.Text = "<FONT color='#ffffff'>&nbsp;| </FONT><A href='AdminArticle.aspx'><FONT color='#ffffff'>发帖审核</FONT></A>";
			}
		}


		protected void Button_Submit_Click(object sender, System.EventArgs e)
		{

			if(!CheckInput())
				return;

			string key = GetArrString(this.TextBox_Key.Text.Trim());
			Search(key, 1);
		}

		private string GetArrString(string key)
		{
			string lastchr = "";
			string arrkey = "";
			for(int i = 0; i < key.Length; i++)
			{
				if(key.Substring(i,1) == " ")
				{
					if(lastchr != " ")
						arrkey += ",";
				}
				else
				{
					arrkey += key.Substring(i,1);
				}
				lastchr = key.Substring(i,1);
			}

			return arrkey;
		}


		private void Searchold(string key, int currentpage)
		{
			//判断是否有AND 或 OR的搜索
			string keyword = key;
			string sql = "SELECT * FROM v_articles WHERE PostID IN (SELECT PostID FROM ForumPosts WHERE CONTAINS(*, '";
			sql += key;
			sql += "'))";

			DataSet ds = new DataSet();
			try
			{
				ds = SearchDataAccess.GetDataSet(sql);
			}
			catch
			{
				try
				{
					key = "\"" + keyword + "\"";
					
					this.Label_LeftResult.Text = "搜索结果：&nbsp;&nbsp;&nbsp;&nbsp;<font color='#cc0000'>" + key + "</font>";
					sql = "SELECT * FROM v_articles WHERE PostID IN (SELECT PostID FROM ForumPosts WHERE CONTAINS(*, '" + key + "'))";
					ds = SearchDataAccess.GetDataSet(sql);
				}
				catch(Exception ex)
				{
					this.Label1.Text = ex.ToString();
					Response.Write("<script defer>alert('查询不成功，请检查关键字的输入内容！');</script>");
					return;
				}
			}


			this.Label_RightResult.Text = ds.Tables[0].Rows.Count.ToString() + "篇文章";

			if(ds.Tables[0].Rows.Count <= PAGE_SIZE)
			{
				this.DropDownList_Page.Visible = false;
				this.DropDownList_Pageb.Visible = false;
				this.Linkbutton_Nextpage.Visible = false;
				this.LinkButton_NextpageB.Visible = false;
				this.LinkButton_Prepage.Visible = false;
				this.LinkButton_PrepageB.Visible = false;
			}
			else
			{
				if(currentpage == 1)
				{
					this.DropDownList_Page.Visible = true;
					this.DropDownList_Pageb.Visible = true;
					this.Linkbutton_Nextpage.Visible = true;
					this.LinkButton_NextpageB.Visible = true;

					this.LinkButton_Prepage.Visible = false;
					this.LinkButton_PrepageB.Visible = false;

					int recnum = ds.Tables[0].Rows.Count;
					int page = recnum / PAGE_SIZE;
					if(recnum % PAGE_SIZE > 0)
						page += 1;

					this.DropDownList_Page.Items.Clear();
					this.DropDownList_Pageb.Items.Clear();
					for(int i = 1; i <= page; i++)
					{
						this.DropDownList_Page.Items.Add(new ListItem("Page " + i.ToString() + " of " + page.ToString() + "  ", i.ToString()));
						this.DropDownList_Pageb.Items.Add(new ListItem("Page " + i.ToString() + " of " + page.ToString() + "  ", i.ToString()));
					}
					
					for(int j = PAGE_SIZE; j < ds.Tables[0].Rows.Count; j++)
					{
						ds.Tables[0].Rows[j]["PostID"] = 0;
					}
				}
				else
				{
					if(currentpage == 1)
					{
						this.LinkButton_Prepage.Visible = false;
						this.LinkButton_PrepageB.Visible = false;
					}
					else
					{
						this.LinkButton_Prepage.Visible = true;
						this.LinkButton_PrepageB.Visible = true;
					}
					if(currentpage.ToString() == this.DropDownList_Page.Items[this.DropDownList_Page.Items.Count - 1].Value)
					{
						this.Linkbutton_Nextpage.Visible = false;
						this.LinkButton_NextpageB.Visible = false;
					}
					else
					{
						this.Linkbutton_Nextpage.Visible = true;
						this.LinkButton_NextpageB.Visible = true;
					}

					for(int i = 0; i < ds.Tables[0].Rows.Count; i++)
					{
						if(i < PAGE_SIZE * (currentpage - 1) || i > PAGE_SIZE * currentpage - 1)
						{
							ds.Tables[0].Rows[i]["PostID"] = 0;
						}
					}
				}
				
				ds.Tables[0].DefaultView.RowFilter = "PostID>0";
			}

			this.DataList1.DataSource = ds.Tables[0].DefaultView;
			this.DataList1.DataBind();

			if(ds.Tables[0].Rows.Count > 0)
			{
				this.Literal_ScrollToTop.Text = "<a href='javascript:window.scrollTo(0,0);'>回本页顶</a>";
																												   }
			else
			{
				this.Literal_ScrollToTop.Text = "";
			}
		}


		private void Search(string key, int currentpage)
		{
			//判断是否有AND 或 OR的搜索
			string[] keyarr = key.Split(',');
			string keyword = key;
			//string sql = "SELECT * FROM v_articles WHERE NOT ApproveUserID IS NULL AND Type='post' AND NOT ArticleURL LIKE '%springofwater.net%' AND PostID IN (SELECT PostID FROM ForumPosts WHERE CONTAINS(*, '";
			string sql = "SELECT * FROM v_articles WHERE type != 'post' and PostID IN (SELECT PostID FROM ForumPosts WHERE CONTAINS(*, '";
			for(int i = 0; i < keyarr.Length; i++)
			{
				if(i == 0)
					sql += "\"" + keyarr[i] + "\"";
				else
					sql += " AND \"" + keyarr[i] + "\"";
			}
			sql += "'))";


			DataSet ds = new DataSet();
			try
			{
				ds = SearchDataAccess.GetDataSet(sql);
			}
			catch(Exception ex)
			{
				this.Label1.Text = ex.ToString();
				Response.Write("<script defer>alert('查询不成功，请检查关键字的输入内容！');</script>");
				return;
			}


			this.Label_RightResult.Text = ds.Tables[0].Rows.Count.ToString() + "篇文章";

			if(ds.Tables[0].Rows.Count <= PAGE_SIZE)
			{
				this.DropDownList_Page.Visible = false;
				this.DropDownList_Pageb.Visible = false;
				this.Linkbutton_Nextpage.Visible = false;
				this.LinkButton_NextpageB.Visible = false;
				this.LinkButton_Prepage.Visible = false;
				this.LinkButton_PrepageB.Visible = false;
			}
			else
			{
				if(currentpage == 1)
				{
					this.DropDownList_Page.Visible = true;
					this.DropDownList_Pageb.Visible = true;
					this.Linkbutton_Nextpage.Visible = true;
					this.LinkButton_NextpageB.Visible = true;

					this.LinkButton_Prepage.Visible = false;
					this.LinkButton_PrepageB.Visible = false;

					int recnum = ds.Tables[0].Rows.Count;
					int page = recnum / PAGE_SIZE;
					if(recnum % PAGE_SIZE > 0)
						page += 1;

					this.DropDownList_Page.Items.Clear();
					this.DropDownList_Pageb.Items.Clear();
					for(int i = 1; i <= page; i++)
					{
						this.DropDownList_Page.Items.Add(new ListItem("Page " + i.ToString() + " of " + page.ToString() + "  ", i.ToString()));
						this.DropDownList_Pageb.Items.Add(new ListItem("Page " + i.ToString() + " of " + page.ToString() + "  ", i.ToString()));
					}
					
					for(int j = PAGE_SIZE; j < ds.Tables[0].Rows.Count; j++)
					{
						ds.Tables[0].Rows[j]["PostID"] = 0;
					}
				}
				else
				{
					if(currentpage == 1)
					{
						this.LinkButton_Prepage.Visible = false;
						this.LinkButton_PrepageB.Visible = false;
					}
					else
					{
						this.LinkButton_Prepage.Visible = true;
						this.LinkButton_PrepageB.Visible = true;
					}
					if(currentpage.ToString() == this.DropDownList_Page.Items[this.DropDownList_Page.Items.Count - 1].Value)
					{
						this.Linkbutton_Nextpage.Visible = false;
						this.LinkButton_NextpageB.Visible = false;
					}
					else
					{
						this.Linkbutton_Nextpage.Visible = true;
						this.LinkButton_NextpageB.Visible = true;
					}

					for(int i = 0; i < ds.Tables[0].Rows.Count; i++)
					{
						if(i < PAGE_SIZE * (currentpage - 1) || i > PAGE_SIZE * currentpage - 1)
						{
							ds.Tables[0].Rows[i]["PostID"] = 0;
						}
					}
				}
				
				ds.Tables[0].DefaultView.RowFilter = "PostID>0";
			}

			this.DataList1.DataSource = ds.Tables[0].DefaultView;
			this.DataList1.DataBind();

			if(ds.Tables[0].Rows.Count > 0)
			{
				this.Literal_ScrollToTop.Text = "<a href='javascript:window.scrollTo(0,0);'>回本页顶</a>";
			}
			else
			{
				this.Literal_ScrollToTop.Text = "";
			}
		}

		private void DataList1_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
		{
			if(e.Item.ItemIndex < 0)
				return;

			DataRowView drv = (DataRowView)e.Item.DataItem;
			Literal objLiteral = (Literal)e.Item.FindControl("Literal_Article");
			objLiteral.Text = "<table border=0 cellpadding=0 cellspacing=0 width='100%'>";
			if(e.Item.ItemIndex == 0)
			{
				objLiteral.Text += "<tr><td height=2 colspan=2 bgcolor='#0033cc'></td></tr>";
			}
			objLiteral.Text += "<tr><td width='100%' height=25>";
			if(drv.Row["url"] == DBNull.Value || drv.Row["url"].ToString() == "")
			{
				objLiteral.Text += "<a class=a1 href='Article.aspx?id=" + drv.Row["PostID"].ToString() + "' target=_blank><font style='font-size:14px'>" + drv.Row["Subject"].ToString() + "</font></a>";
			}
			else
			{
				objLiteral.Text += "<a class=a1 href='" + drv.Row["url"].ToString() + "' target=_blank><font size=+1>" + drv.Row["Subject"].ToString() + "</font></a>";
			}
			//objLiteral.Text += "</td><td nowrap><a href='AllArticles.aspx?id=" + drv.Row["UserID"].ToString() + "&name=" + Server.UrlEncode(drv.Row["NickName"].ToString()) + "' target=_blank>" + drv.Row["NickName"].ToString() + "</a></td></tr>\n";
            objLiteral.Text += "</td><td nowrap></td></tr>\n";

			string chapter = drv.Row["BibleChapter"].ToString();
			string section = drv.Row["BibleSection"].ToString();
			string chapter_to = drv.Row["BibleChapter_To"].ToString();
			string section_to = drv.Row["BibleSection_To"].ToString();
			string scripture = drv.Row["BibleTitle"].ToString() + "&nbsp;&nbsp;" + chapter;
			if(section != "")
				scripture += "∶" + section;
			if(chapter_to != "" || section_to != "")
				scripture += "&nbsp;—&nbsp;";
			if(chapter_to != "")
				scripture += chapter_to;
			if(section_to != "")
				scripture += "∶" + section_to;
			objLiteral.Text += "<tr><td height=25 colspan=2 style='FONT-SIZE:12px;'><a class=a1 href='BibleTools.aspx?title=" + drv.Row["BibleTitle"].ToString() + "&c=" + chapter + "&s=" + section + "' target=_blank>" + scripture + "</a></td></tr>\n"; 
//			if(drv.Row["Summary"].ToString() == "")
//			{
//				objLiteral.Text += "<tr><td height=25 colspan=2 style='FONT-SIZE:12px; TEXT-HEIGHT:150%;'>" + (drv.Row["Body"].ToString().Length>500?drv.Row["Body"].ToString().Substring(0,500):drv.Row["Body"].ToString().ToString()) + "</td></tr>\n";
//			}
//			else
//			{
//				objLiteral.Text += "<tr><td height=25 colspan=2 style='FONT-SIZE:12px; TEXT-HEIGHT:150%;'>" + drv.Row["Summary"].ToString() + "</td></tr>\n";
//			}

			objLiteral.Text += "<tr><td height=25 colspan=2 style='FONT-SIZE:12px; TEXT-HEIGHT:150%;' class=f>" + ShowArticlePart(drv.Row["Body"].ToString()) + "</td></tr>\n";

			objLiteral.Text += "<tr><td height=1 colspan=2 bgcolor='#000000'></td></tr>\n";
			string[] keyarr = GetArrString(this.TextBox_Key.Text.Trim()).Split(',');
			objLiteral.Text += "<tr><td height=25 colspan=2 style='FONT-SIZE:14px; TEXT-HEIGHT:150%;'>文章包含：";
			for(int k = 0; k < keyarr.Length; k++)
			{
				objLiteral.Text += keyarr[k] + "(" + this.indexofnum(drv.Row["Body"].ToString(), keyarr[k]) + ")&nbsp;&nbsp;";
			}
			objLiteral.Text += "</td></tr>";
			int numberofvisits = Convert.ToInt32(drv.Row["NumberOfVisits"]);
			int numberofyes, numberofno;
			if(drv.Row["Vote_yes"] == DBNull.Value)
				numberofyes = 0;
			else
				numberofyes = Convert.ToInt32(drv.Row["Vote_yes"]);

			if(drv.Row["Vote_no"] == DBNull.Value)
				numberofno = 0;
			else
				numberofno = Convert.ToInt32(drv.Row["Vote_no"]);

			numberofvisits = numberofno + numberofyes;

			if(numberofyes > 0 && numberofvisits > 0)
			{
				decimal p = Convert.ToDecimal(numberofyes) / Convert.ToDecimal(numberofvisits);
				objLiteral.Text += "<tr><td height=25 colspan=2 style='COLOR:#003399'>" + numberofvisits.ToString() + "位读者中" +
					numberofyes.ToString() + "位（" + p.ToString("P") + "）认为本文对他们有帮助</td></tr>\n";
			}

			objLiteral.Text += "<tr><td height=2 colspan=2 bgcolor='#0033cc'></td></tr><tr><td height=10 colspan=2></td></tr></table>\n"; 
		}


		private bool CheckInput()
		{
			this.Label_LeftResult.Text = "搜索结果：&nbsp;&nbsp;&nbsp;&nbsp;<font color='#cc0000'>" + this.TextBox_Key.Text.Trim() + "</font>";
			
			return true;
		}

        protected void DropDownList_Page_SelectedIndexChanged1(object sender, EventArgs e)
        {
            if (flag)
                GoPage(Convert.ToInt32(this.DropDownList_Page.SelectedValue));
        }

     
        protected void DropDownList_Pageb_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (flag)
                GoPage(Convert.ToInt32(this.DropDownList_Pageb.SelectedValue));
        }


		private void GoPage(int page)
		{
			flag = false;
			this.DropDownList_Page.SelectedValue = page.ToString();
			this.DropDownList_Pageb.SelectedValue = page.ToString();
			flag = true;

			if(!CheckInput())
				return;

			string key = this.TextBox_Key.Text.Trim();
			this.Search(GetArrString(key), page);
		}
			

		protected void LinkButton_Prepage_Click1(object sender, EventArgs e)
		{
			GoPage(Convert.ToInt32(this.DropDownList_Page.SelectedValue) - 1);
		}


        protected void Linkbutton_Nextpage_Click1(object sender, EventArgs e)
        {
            GoPage(Convert.ToInt32(this.DropDownList_Page.SelectedValue) + 1);
        }

        protected void LinkButton_PrepageB_Click(object sender, EventArgs e)
        {
            GoPage(Convert.ToInt32(this.DropDownList_Page.SelectedValue) - 1);
        }

        protected void LinkButton_NextpageB_Click(object sender, EventArgs e)
        {
            GoPage(Convert.ToInt32(this.DropDownList_Page.SelectedValue) + 1);
        }

		private string ShowArticlePart(string body)
		{
			int at, len;
			string p = "", part = "";
			string[] keyarr = GetArrString(this.TextBox_Key.Text.Trim()).Split(',');

			string key = keyarr[0];
			len = key.Length;
			body = thinbody(body);
			for(int i = 1; i < 3; i++)
			{
				p = "";
				if(i > 1 && keyarr.Length > i)
				{
					key = keyarr[i - 1];
				}
				else
				{
					key = keyarr[0];
				}
				len = key.Length;
				at = body.IndexOf(key);
				if(at >=0)
				{
					//前段处理
					int j;
					for(j = 0; j < 30; j++)
					{
						if(at-j-1>=0 && body.Substring(at-j-1,1) != "," && body.Substring(at-j-1,1) != "，" && body.Substring(at-j-1,1) != "。" && body.Substring(at-j-1,1) != ".")
						{
							//part = body.Substring(at-j-1,1) + part;
							p = body.Substring(at-j-1,1) + p;
						}
						else
						{
							break;
						}
					}

					p += key;
					//后段处理
					for(j = 0; j < 120 - p.Length; j++)
					{
						try
						{
							p += body.Substring(at + len + j, 1);
						}
						catch
						{
							break;
						}
					}

					body = body.Replace(p, "");
					part += p;
					part = part + "<b>...</b>";
				}
			}
			string tempart = part.Replace("<b>...</b>","");
			if(tempart.Length == 0)
			{
				int l = 180;
				if(body.Length < l)
					return body;
				else
					return body.Substring(0, l) + "<b>...</b>";
			}

			for(int n = 0; n < keyarr.Length; n++)
			{
				part = part.Replace(keyarr[n], "<font color=red>" + keyarr[n] + "</font>");
			}

			return part;
		}

		private string thinbody(string body)
		{
			bool flag = true;
			string newbody = "";
			for(int i = 0; i < body.Length; i++)
			{
				if(body.Substring(i,1) == "<")
				{
					flag = false;
				}
				else if(body.Substring(i, 1) == ">")
				{
					flag = true;
				}
				else if(flag)
				{
					newbody += body.Substring(i, 1);
				}
			}

			body = newbody;
			newbody = "";
			for(int i = 0; i < body.Length; i++)
			{
				if(body.Substring(i,1) == "&")
				{
					flag = false;
				}
				else if(body.Substring(i, 1) == ";")
				{
					flag = true;
				}
				else if(flag)
				{
					newbody += body.Substring(i, 1);
				}
			}
			
			return newbody;
		}

		private int indexofnum(string body, string key)
		{
			int num = 0;
			int start = 0;
			int at = 0;
			while(start < body.Length - 1)
			{
				at = body.IndexOf(key, start);
				if(at >= 0)
				{
					num += 1;
					start = at + key.Length;
				}
				else
				{
					break;
				}
			}

			return num;
		}

       
     

        
        
       

         

	}
}
